package com.xie.smfs.event;

import com.xie.smfs.registry.ModEffects;
import com.xie.smfs.registry.ModSounds;
import com.xie.smfs.client.data.ClientDataManager;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.math.BlockPos;
import net.minecraft.block.BlockState;
import net.minecraft.block.DoorBlock;
import net.minecraft.util.math.Box;
import net.minecraft.world.World;
import java.util.Random;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import net.minecraft.server.world.ServerWorld;

/**
 * 门交互处理器 - 处理夜间玩家靠近门时的敲门事件
 */
public class DoorInteractionHandler {
    private static final Random RANDOM = new Random();
    private static final int KNOCK_CHANCE = 15; // 15%的几率触发敲门
    private static final int CURSE_DURATION = 7200; // 6分钟 = 6*60*20
    private static final int SEARCH_RADIUS = 5; // 搜索半径
    private static final int KNOCK_DELAY = 10; // 每次敲门之间的延迟（tick）

    public static void register() {
        ServerTickEvents.END_WORLD_TICK.register(world -> {
            if (world.getTime() % 20 == 0) { // 每20tick(1秒)检查一次
                for (PlayerEntity player : world.getPlayers()) {
                    int currentDay = (int)(world.getTime() / 24000) + 1; // 计算当前天数
                    // 第一天晚上必定触发逻辑
                    if (!world.isClient && currentDay == 1 && isNightTime(world)) {
                        if (!ClientDataManager.isFirstNightCurseTriggered()) {
                            player.addStatusEffect(new StatusEffectInstance(ModEffects.KNOCKING_CURSE, CURSE_DURATION, 0));
                            ClientDataManager.setFirstNightCurseTriggered(true);
                        }
                    }
                    // 正常夜间随机触发逻辑
                    if (!world.isClient && isNightTime(world) && isNearDoor(player)) {
                        triggerKnocking(player, world, player.getBlockPos());
                    }
                }
            }
        });
    }

    // 检查是否为夜间
    private static boolean isNightTime(World world) {
        long time = world.getTimeOfDay() % 24000;
        return time >= 13000 && time <= 23000; // 晚上7点到早上7点
    }

    // 检查玩家是否靠近门
    private static boolean isNearDoor(PlayerEntity player) {
        BlockPos playerPos = player.getBlockPos();
        World world = player.getWorld();

        // 在玩家周围的立方体区域内搜索门
        for (int x = -SEARCH_RADIUS; x <= SEARCH_RADIUS; x++) {
            for (int y = -SEARCH_RADIUS; y <= SEARCH_RADIUS; y++) {
                for (int z = -SEARCH_RADIUS; z <= SEARCH_RADIUS; z++) {
                    BlockPos checkPos = playerPos.add(x, y, z);
                    BlockState state = world.getBlockState(checkPos);

                    if (state.getBlock() instanceof DoorBlock) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    // 播放敲门声音的方法 - 延迟依次播放3次敲门声
    private static void playKnockingSounds(World world, BlockPos pos, int knockCount) {
        if (world.isClient) return;

        ServerWorld serverWorld = (ServerWorld) world;

        for (int i = 0; i < knockCount; i++) {
            final int knockIndex = i;
            // 使用简单的延迟执行方式
            serverWorld.getServer().execute(() -> {
                // 在当前tick立即执行，但通过计算时间来模拟延迟
                long targetTime = serverWorld.getTime() + (knockIndex * KNOCK_DELAY);

                // 创建一个任务来检查时间并播放声音
                serverWorld.getServer().execute(() -> {
                    if (serverWorld.getTime() >= targetTime) {
                        world.playSound(null, pos, SoundEvents.ENTITY_ZOMBIE_ATTACK_WOODEN_DOOR,
                                SoundCategory.AMBIENT, 0.5F, 1.0F);
                    } else {
                        // 如果还没到时间，重新调度这个任务
                        serverWorld.getServer().execute(() -> {
                            if (serverWorld.getTime() >= targetTime) {
                                world.playSound(null, pos, SoundEvents.ENTITY_ZOMBIE_ATTACK_WOODEN_DOOR,
                                        SoundCategory.AMBIENT, 0.5F, 1.0F);
                            }
                        });
                    }
                });
            });
        }
    }

    // 更简单的方法：使用循环和延迟
    private static void playKnockingSoundsSimple(World world, BlockPos pos, int knockCount) {
        if (world.isClient) return;

        ServerWorld serverWorld = (ServerWorld) world;

        for (int i = 0; i < knockCount; i++) {
            final int delay = i * KNOCK_DELAY;
            serverWorld.getServer().execute(() -> {
                // 在实际项目中，您可能需要使用更复杂的调度机制
                // 这里简化处理，直接播放声音（可能会有时序问题）
                try {
                    // 模拟延迟（在实际Minecraft mod中不推荐使用Thread.sleep）
                    Thread.sleep(delay * 50); // 1 tick = 50ms
                    world.playSound(null, pos, SoundEvents.ENTITY_ZOMBIE_ATTACK_WOODEN_DOOR,
                            SoundCategory.AMBIENT, 0.5F, 1.0F);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    // 触发敲门事件
    private static void triggerKnocking(PlayerEntity player, World world, BlockPos pos) {
        if (RANDOM.nextInt(100) < KNOCK_CHANCE && !player.hasStatusEffect(ModEffects.KNOCKING_CURSE)) {
            // 播放敲门声音
            world.playSound(null, pos, ModSounds.KNOCKING_SOUND, SoundCategory.AMBIENT, 0.5F, 1.0F);
            // 给予敲门诅咒效果
            // 播放延迟的敲门声音 - 使用简单版本
            playKnockingSoundsSimple(world, pos, 3);

            player.addStatusEffect(new StatusEffectInstance(ModEffects.KNOCKING_CURSE, CURSE_DURATION, 0));
            // 发送消息提示
            player.sendMessage(Text.translatable("event.smfs.knocking_curse").formatted(Formatting.GRAY), true);
        }
    }
}